<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title>沙立方</title>
		<meta name="description" content="">
		<meta name="keywords" content="">
		<meta name="renderer" content="webkit">
		<!-- 设置缩放 -->
		<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimal-ui" />
		<!-- 可隐藏地址栏，仅针对IOS的Safari（注：IOS7.0版本以后，safari上已看不到效果） -->
		<meta name="apple-mobile-web-app-capable" content="yes" />
		<!-- 仅针对IOS的Safari顶端状态条的样式（可选default/black/black-translucent ） -->
		<meta name="apple-mobile-web-app-status-bar-style" content="black" />
		<!-- IOS中禁用将数字识别为电话号码/忽略Android平台中对邮箱地址的识别 -->
		<meta name="format-detection" content="telephone=no, email=no" />
		<!-- 启用360浏览器的极速模式(webkit) -->
		<meta name="renderer" content="webkit">
		<!-- 避免IE使用兼容模式 -->
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<!-- 针对手持设备优化，主要是针对一些老的不识别viewport的浏览器，比如黑莓 -->
		<meta name="HandheldFriendly" content="true">
		<!-- 微软的老式浏览器 -->
		<meta name="MobileOptimized" content="320">
		<!-- uc强制竖屏 -->
		<meta name="screen-orientation" content="portrait">
		<!-- QQ强制竖屏 -->
		<meta name="x5-orientation" content="portrait">
		<!-- UC强制全屏 -->
		<meta name="full-screen" content="yes">
		<!-- QQ强制全屏 -->
		<meta name="x5-fullscreen" content="true">
		<!-- UC应用模式 -->
		<meta name="browsermode" content="application">
		<!-- QQ应用模式 -->
		<meta name="x5-page-mode" content="app">
		<!-- windows phone 点击无高光 -->
		<meta name="msapplication-tap-highlight" content="no">
		<meta http-equiv="Cache-Control" content="no-siteapp" />
		<link rel="icon" type="image/png" href="../../assets/i/favicon.png">
		<link rel="stylesheet" href="../../assets/css/amazeui.min.css" />
		<link rel="stylesheet" href="../../assets/choice/iosSelect.css">
		<link rel="stylesheet" href="../../assets/css/app.css">
		<link rel="stylesheet" href="../../assets/css/yttApp.css">
	</head>

	<body class="bg-fff add_child">
		<header data-am-widget="header" class="am-header bg-white am-header-fixed borBottom bg-085492">
			<div class="am-header-left am-header-nav text-black padding-left05" id="goBackDivs">
				<a  href="javascript:history.go(-1)" class="text-black" id="goBackIcon">
				  	<i class="am-align-left am-margin-0 am-icon-angle-left am-icon-md text-black co-fff"></i>
				  </a> 
			</div>
			<h1 class="am-header-title teblack">
				<a href="#title-link" class="co-fff">添加孩子信息</a>
			</h1>
		</header>
		
		<div class="am-container am-padding-sm">
			<form class="am-form am-margin-0 reg" method="get" action="" id="regfrom" style="margin-bottom:50px!important;">
				<div class="am-form-group imdDiv" style="border-radius:10px;">
					<div class="headerdivs">
						<div id="preview">
							 <img src="../../img/noChild.jpg"/>
						</div>
						<input type="file" onchange="preview(this)" id="file"/>
					</div>
				</div>
				<div class="am-form-group">
					<label for="childuser"><font style="color:red;">*</font>孩子姓名</label>
					<input type="text" class="public" id="childuserName" placeholder="请输入孩子姓名" required />
				</div>
				<div class="font12 name_validation" style="display:none;color:red;">孩子姓名必填</div>
				<div class="am-form-group">
					<label for="childuser"><font style="color:red;">*</font>孩子出生日期</label>
					<input type="text" id="childuserBirthday" class="bg-FFFBF2 public" readonly onfocus="this.blur();" />
				</div>
				<div class="font12 birth_validation" style="display:none;color:red;">孩子出生日期必填</div>
				<div class="am-form-group">
					<label for="height"><font style="color:red;">*</font>孩子身高(单位：cm)</label>
					<input type="number" id="height" value="" class="public" placeholder="请输入孩子身高" required onfocus="this.blur();"/>
				</div>
				<div class="font12 height_validation" style="display:none;color:red;">孩子身高必填</div>
				<div class="am-form-group">
					<label for="weight"><font style="color:red;">*</font>孩子体重(单位：kg)</label>
					<input type="number" id="weight" value="" class="public" placeholder="请输入孩子体重" required onfocus="this.blur();"/>
				</div>
				<div class="font12 weight_validation" style="display:none;color:red;">孩子体重必填</div>
				<div class="am-form-group">
					<label class="am-block"><font style="color:red;">*</font>性别</label>
					<label class="am-radio-inline regradio">
				        <input type="radio" value="0" name="sex" class="sexs" id="sexn" checked="true" />
				        <label for="sexn">男</label>
					</label>
					<label class="am-radio-inline regradio">
			            <input type="radio"  value="1" name="sex" class="sexs" id="sexv">
			            <label for="sexv" >女</label>
					</label>
				</div>
				<div class="am-form-group">
					<label for="schoolname"><font style="color:red;">*</font>选择上课校区</label>
					<div class="select_div posi-rela">
						<select id="schoolname">
							
						</select>
					</div>
				</div>
				<div class="am-form-group">
					<label><font style="color:red;">*</font>期望上课时间</label>
					<div class="selectTimeDiv">
							<div data-am-widget="tabs" class="am-tabs am-tabs-d2" style="margin:10px 0!important">
						      <ul class="am-tabs-nav am-cf">
						          <li class="am-active"><a href="[data-tab-panel-0]">周一</a></li>
						          <li class=""><a href="[data-tab-panel-1]">周二</a></li>
						          <li class=""><a href="[data-tab-panel-2]">周三</a></li>
						          <li class=""><a href="[data-tab-panel-3]">周四</a></li>
						          <li class=""><a href="[data-tab-panel-4]">周五</a></li>
						          <li class=""><a href="[data-tab-panel-5]">周六</a></li>
						          <li class=""><a href="[data-tab-panel-6]">周天</a></li>
						      </ul>
						      <div class="am-tabs-bd" id="timeDtaUl">
						          <div data-tab-panel-0 class="am-tab-panel am-active timeUls">
						               
						           </div>
						          <div data-tab-panel-1 class="am-tab-panel timeUls">
						          </div>
						          <div data-tab-panel-2 class="am-tab-panel timeUls">
						          </div>
						          <div data-tab-panel-3 class="am-tab-panel timeUls">
						          </div>
						          <div data-tab-panel-4 class="am-tab-panel timeUls">
						          </div>
						          <div data-tab-panel-5 class="am-tab-panel timeUls">
						          </div>
						          <div data-tab-panel-6 class="am-tab-panel timeUls">
						          </div>
						      </div>
						  </div>
					</div>
				</div>
				<div class="font12 time_validation" style="display:none;color:red;">孩子期望日期必填</div>
			</form>
		</div>
		<button id="register" type="button">确认</button>
		<div class="am-modal am-modal-loading am-modal-no-btn radius4" tabindex="-1" id="my-modal-loading" data-am-modal="{closeViaDimmer: 0}">
		  <div class="am-modal-dialog" style="border-radius: 4px;">
		    	<div class="am-modal-hd">加载中...</div>
			    <div class="am-modal-bd">
			      <span class="am-icon-spinner am-icon-spin"></span>
			    </div>
		  </div>
		</div>
		
		<div class="am-modal am-modal-alert" tabindex="-1" id="alert1" data-am-modal="{closeViaDimmer: 0}">
		  <div class="am-modal-dialog" style="border-radius: 4px;">
		    	<div class="am-modal-hd"></div>
			   	<div class="am-modal-bd alert1"></div>
		   		<div class="am-modal-footer">
		      		<span class="am-modal-btn">确定</span>
		    	</div>
	  		</div>
		</div>
		
		<script src="../../assets/js/jquery.min.js"></script>
		<script src="../../assets/js/jquery.cookie.js"></script>
		<script src="../../assets/js/amazeui.min.js"></script>
		<script src="../../assets/js/fastclick.min.js"></script>
		<script src="../../assets/choice/iosSelect.js"></script>
	    <script src="../../assets/choice/data.js"></script>
		<script src="../../js/comm.js"></script>
		<script src="../../js/slf.js"></script>
		<script>
		var userId=GetUrl("userId");
		var childrenId=GetUrl("childrenId");
		var imgurl="";
		$(function(){
			$('.public').on('click',function(){
				console.log("fd")
				$('.name_validation').css('display','none');
				$('.birth_validation').css('display','none');
				$('.height_validation').css('display','none');
				$('.weight_validation').css('display','none');
			})
			//禁止查看今天之后的信息
		    var nowTemp = new Date();
		    var nowDay = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0).valueOf();
		    var nowMoth = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), 1, 0, 0, 0, 0).valueOf();
		    var nowYear = new Date(nowTemp.getFullYear(), 0, 1, 0, 0, 0, 0).valueOf();
		    var $myStart2 = $('#childuserBirthday');
		    var checkin = $myStart2.datepicker({
		    	onRender: function(date, viewMode) {
		            // 默认 days 视图，与当前日期比较
		            var viewDate = nowDay;
		            switch (viewMode) {
		              // moths 视图，与当前月份比较
		              case 1:
		                viewDate = nowMoth;
		                break;
		              // years 视图，与当前年份比较
		              case 2:
		                viewDate = nowYear;
		                break;
		            }
		
		            return date.valueOf() > viewDate ? 'am-disabled' : '';
		          }
		    })
			/* 默认获取校区  */
			getschoolName();
			//点击体重
			var showGeneralDom = document.querySelector('#weight');
		    showGeneralDom.addEventListener('click', function () {
		        var suId = showGeneralDom.dataset['su_id'];
		        var suValue = showGeneralDom.dataset['su_value'];
		        var weiId = showGeneralDom.dataset['wei_id'];
		        var weiValue = showGeneralDom.dataset['wei_value'];
		        var sanguoSelect = new IosSelect(2, 
		            [suData, weiData],
		            {
		                title: '体重（kg）',
		                itemHeight: 35,
		                oneLevelId: suId,
		                twoLevelId: weiId,
		                callback: function (selectOneObj, selectTwoObj) {
		                    $("#weight").val(selectOneObj.value + '.' + selectTwoObj.value)
		                }
		        });
		    });
		    //点击身高
		    var showBankDom = document.querySelector('#height');
		    showBankDom.addEventListener('click', function () {
		        var bankSelect = new IosSelect(1, 
		            [datas],
		            {
		                container: '.container',
		                title: '身高选择',
		                itemHeight: 50,
		                itemShowCount: 3,
		                callback: function (selectOneObj) {
		                    $("#height").val(selectOneObj.value)
		                },
		                fallback: function () {
		                    console.log(1);
		                },
		                maskCallback: function () {
		                    console.log(2);
		                }
		        });
		    });
			if(childrenId!=undefined&&childrenId!=""&&childrenId!=null){
				//查询孩子信息
				slf.ajax({
					url : "/childrenController/getChildren",
					dataType : "json",
					type: 'POST',
					param : {
						childrenId : childrenId,
					},
					//contentType: "application/text; charset=utf-8",
					success : function(data){
						console.log(data)
						console.log("获取孩子信息")
						if(data.res ==1){
							 var data=data.obj[0];
							$("#childuserName").val(data.name);
							$("#childuserBirthday").datepicker('setValue', data.birthdayStr);
							$("#height").val(data.height);
							$("#weight").val(data.weight);
							console.log(data.sex)
							$(".sexs").each(function(){
								if($(this).val()==data.sex){
									$(this).attr("checked",true)
								}else{
									$(this).removeAttr("checked")
								}
							})
							if(data.headPortrait=="../img/boy.png"){
								$("#preview img").attr("src",'../'+data.headPortrait)
							}else{
								$("#preview img").attr("src",data.headPortrait)
							}
							$("#schoolname").val(data.schoolId);
							//遍历时间段
							var timeList=data.slfChildExpectedTimeList;
							if(data.slfChildExpectedTimeList==undefined||data.slfChildExpectedTimeList==null||data.slfChildExpectedTimeList==""){
								
							}else{
								for(var key in timeList){
	                               var times=[];
	                               times=timeList[key];//日期段
								   $(".timeUls").each(function(){
									   if($(this).index()==key-1){
										   $(this).find(".timeDa").each(function(){
											   for(var i=0;i<times.length;i++){
												   if($(this).html()==times[i]){
													   $(this).addClass("timeActive")
												   }
											   }
										   })
									   }
								   }) 

								} 
							}
							
						}
					},error:function(data){
						console.log("失败")
						console.log(data)
						console.log("...")
					}
				});
			}
			//追加数据到时间块
			var html="";
			html+='<div class="timeDatas"><span class="timeDa">10:00-11:00</span></div>'
		    html+='<div class="timeDatas"><span class="timeDa">11:00-12:00</span></div>'  
		    html+='<div class="timeDatas"><span class="timeDa">14:00-15:00</span></div>'  
		    html+='<div class="timeDatas"><span class="timeDa">15:00-16:00</span></div>'   
		    html+='<div class="timeDatas"><span class="timeDa">16:00-17:00</span></div>'   
		    html+='<div class="timeDatas"><span class="timeDa">17:00-18:00</span></div>'   
		    html+='<div class="timeDatas"><span class="timeDa">19:00-20:00</span></div>'   
		    html+='<div class="timeDatas"><span class="timeDa">20:00-21:00</span></div>'
		    $(".timeUls").append(html);
		    //选择时间段事件
		    $(".timeDatas").click(function(){
		    	$('.time_validation').css('display','none');
		    	if($(".timeActive").length>14){
		    		if($(this).find(".timeDa").hasClass("timeActive")){
		    			$(this).find(".timeDa").removeClass("timeActive")
		    		}else{
		    			$(".alert1").html("最多只能选择15个时间段！")
		    			$("#alert1").modal();
		    		}
		    	}else{
		    		if($(this).find(".timeDa").hasClass("timeActive")){
			    		$(this).find(".timeDa").removeClass("timeActive")
			    	}else{
			    		$(this).find(".timeDa").addClass("timeActive")
			    	}
		    	}
		    })
			$("#register").click(function(){
				var name=$.trim($("#childuserName").val());
				var birthday=$.trim($("#childuserBirthday").val());
				birthday =birthday.split("-").join("/");
				var height = $.trim($("#height").val());
				var weight = $.trim($("#weight").val());
				var schoolId = $.trim($("#schoolname").find("option:selected").val());
				var schoolName = $.trim($("#schoolname").find("option:selected").text());
				var sex=$.trim($("input[name='sex']:checked").val());
				var parms={};
				var time='';
				$("#timeDtaUl .timeUls").each(function(){
					 if($(this).find(".timeActive").length!=0){
						var weekData='';
						var indexNum=$(this).index()+1;
						switch(indexNum)
						{
						case 1:
						  weekData='周一'
						  break;
						case 2:
						  weekData='周二'
						  break;
						case 3:
						  weekData='周三'
						  break;
						case 4:
						  weekData='周四'
						  break;
						case 5:
						  weekData='周五'
						  break;
						case 6:
						  weekData='周六'
						  break;
						case 7:
						  weekData='周天'
						  break;
					 }
					 $(this).find(".timeActive").each(function(){
						 var timeDatas=$(this).html();
						 time+=weekData+"/"+timeDatas+",";
					 })
				   }
				})
				
				var url="";
				if(imgurl==""||imgurl==undefined||imgurl==null){
					console.log("未上传头像")
					imgurl=$("#preview img").attr("src");
					if(imgurl=="../../img/boy.png"||imgurl=='../../img/noChild.jpg'){
						imgurl="../img/boy.png"
					}
				}
				if(name == ""){
					$('.name_validation').css('display','block');
				}else if(birthday == ""){
					$('.bir_validation').css('display','block');
				}else if(height == ""){
					$('.height_validation').css('display','block');
				}else if(weight == ""){
					$('.weight_validation').css('display','block');
				}else if(time==''||time ==null){
					$('.time_validation').css('display','block');
				}else{
					if(childrenId!=undefined&&childrenId!=""&&childrenId!=null){
						console.log("修改");
						console.log(imgurl)
						slf.ajax({
							url : "/childrenController/updateChildren",
							param :{
								childrenId:childrenId,
								name : name,
								height :height,
								weight :weight,
								birthday:birthday,
								schoolId:schoolId,
								schoolName:schoolName,
								sex:sex,
								parameter:time,
								headPortrait: imgurl,
							},
							success : function(data){
								if(data.res ==1){
									values = "成功！";
									$('.alert1').text(values);
									$('#alert1').modal(); 
									window.location.href="child_list.html"; 
									console.log(data.resMsg);
								}else{
									console.log(data.resMsg);
								}
							}
						});
					}else{
						console.log("新增");
						console.log(imgurl)
						slf.ajax({
							url : "/childrenController/insertChildren",
							param :{
								name : name,
								height :height,
								weight :weight,
								birthday:birthday,
								schoolId:schoolId,
								schoolName:schoolName,
								sex:sex,
								parameter:time,
								headPortrait: imgurl,
							},
							success : function(data){
								if(data.res ==1){
									values = "成功！";
									$('.alert1').text(values);
									$('#alert1').modal(); 
									window.location.href="child_list.html"; 
									console.log(data.resMsg);
								}else{
									console.log(data.resMsg);
								}
							}
						});
					}
				}
			})
		});
        /* 上传头像 预览 */
        function preview(file) {
            var prevDiv = document.getElementById('preview');
            if (file.files && file.files[0]) {
                var reader = new FileReader();
                reader.onload = function(evt){
                    prevDiv.innerHTML = '<img class="touxiang" src="' + evt.target.result + '" />';
                }
                reader.readAsDataURL(file.files[0]);
            } else {
                prevDiv.innerHTML = '<div style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';
            }
            $("#my-modal-loading").modal('open')
            imgUpload();
        }
        function imgUpload(){
            var file = document.getElementById("file").files[0];
            var formData = new FormData();
            formData.append('file', file);
            $.ajax({
                url : "/web/attachment/upload",
                type: "post",
                data: formData,
                contentType: false,
                processData: false,
                mimeType: "multipart/form-data",
                success: function (data) {
                    data = eval('('+data+')');
                    console.log(data);
                    imgurl=data.obj.path;
                    $("#my-modal-loading").modal('close')
                },
                error: function (data) {
                    console.log(data);
                }
            });
        }
		/* 获取校区  */
		function getschoolName(){
			slf.ajax({
				url : "/register/getSchoolList",
				success : function(data){
					if(data.obj.length > 0){
						var school = data.obj;
						var html = "";
						for(var i = 0; i < school.length; i++){
							html += "<option value="+school[i].id+">"+school[i].value+"</option>"
						}
						$("#schoolname").append(html);
					}
				}
			});
		}
		</script>
	</body>

</html>